package com.toutoushidao.ssm.util;

import com.mongodb.BasicDBObject;
import com.mongodb.client.MongoCursor;
import com.toutoushidao.ssm.dao.MongoDbDao;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 周期奖励
 */
@Component
public class CycleReward {

    @Autowired
    public MongoDbDao dbDao;

    // TODO 调整执行周期时间
    //    @Scheduled(cron = "0 0 0 0 0 7")// 每周日0:00
    @Scheduled(cron = "0 0 0 */2 * ?")// 每两天0:00
//    @Scheduled(initialDelay = 0, fixedDelay = 600000)// 每十分钟一次
    public void cycleExecute() {
        if (rankReward()) {// 当发放奖励成功时, 再清空得分
            rankClean();
        }
    }

    public void rankClean() {
        BasicDBObject whereDoc = new BasicDBObject();
        BasicDBObject updDoc = new BasicDBObject();
        updDoc.put("maxScore", 0);
        dbDao.update("user", whereDoc, updDoc);

    }

    /**
     * 结算金币奖励
     */
    public boolean rankReward() {
        int tenthScore = getTenthScore();
        System.out.println(tenthScore);
        boolean incResult = coinHandle(tenthScore);
        return incResult;
    }

    public int getTenthScore() {
        List<Document> conditionList = new ArrayList<>();
        Document matchDoc = new Document();// 仅显示最高分>0的用户
        matchDoc.put("maxScore", new Document("$gt", 0));
        conditionList.add(new Document("$match", matchDoc));
        Document groupDoc = new Document();// 统计人数
        groupDoc.put("_id", "$maxScore");
        groupDoc.put("count", new Document("$sum", 1));
        conditionList.add(new Document("$group", groupDoc));
        conditionList.add(new Document("$sort", new BasicDBObject("_id", -1)));// 得分逆序
        conditionList.add(new Document("$limit", 10));// 取十条
        MongoCursor<Document> aggregateList = dbDao.aggregate("user", conditionList);// 获取前十个最高的得分
        int count = 0;
        int score = 0;
        while (aggregateList.hasNext()) {
            Document doc = aggregateList.next();
            count += (int) doc.get("count");
            if (count >= 10) {
                score = (int) doc.get("_id");
                break;
            }
        }
        return score;
    }

    public boolean coinHandle(int tenthScore) {
        BasicDBObject whereDoc = new BasicDBObject();
        whereDoc.put("maxScore", new BasicDBObject("$gte", tenthScore));
        BasicDBObject incDoc = new BasicDBObject("coinCnt", 100);
//        incDoc.put("coinCnt", 100);
        boolean incResult = dbDao.updateInc("user", whereDoc, incDoc);
        return incResult;
    }
}
